package com.len.controller;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.len.entity.BannerEntity;
import com.len.service.BannerService;
import com.len.util.JsonUtil;
import com.len.util.ReType;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@Controller
@RequestMapping(value = "/shop/banner")
@Slf4j
@RequiresPermissions("banner:showList")
public class BannerController {

    @Resource
    private BannerService bannerService;

    @GetMapping(value = "showList")
    public String showList() {
        return "/shop/banner/bannerList";
    }

    @GetMapping(value = "showAdd")
    public String showAdd() {
        return "/shop/banner/add";
    }

    @GetMapping(value = "showUpdate")
    public String showUpdate(@RequestParam String id,Model model) {
        BannerEntity bannerEntity = bannerService.getEntity(id);
        model.addAttribute("entity", bannerEntity);
        return "/shop/banner/update";
    }

    @GetMapping(value = "getList")
    @ResponseBody
    public String getList(String page, String limit) {

        Page<BannerEntity> tPage = new Page<>(Integer.parseInt(page), Integer.parseInt(limit));
        tPage = bannerService.getList(tPage);
        ReType reType = new ReType(tPage.getTotal(), tPage.getResult());

        return JSON.toJSONString(reType);
    }

    @PostMapping(value = "add")
    @ResponseBody
    public JsonUtil add(BannerEntity bannerEntity) {
        try {
            bannerService.add(bannerEntity);
            return JsonUtil.success("添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error(e.getMessage());
        }
    }

    @PostMapping(value = "update")
    @ResponseBody
    public JsonUtil update(BannerEntity bannerEntity) {
        try {
            bannerService.update(bannerEntity);
            return JsonUtil.success("修改成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error(e.getMessage());
        }
    }

    @PostMapping(value = "delete")
    @ResponseBody
    public JsonUtil delete(@RequestParam String id) {
        try {
            bannerService.del(id);
            return JsonUtil.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.error(e.getMessage());
        }
    }

}
